<template>
  <div class="content">
    <!-- 互动社区 顶部搜索栏 -->
    <div class="top-contain">
      <div class="logoBlock">
        <!-- <el-avatar :size="50"></el-avatar>
                <div>用户名</div> -->
        <h1>互动社区</h1>
      </div>
      <div class="searchQuestion">
        <el-input placeholder="搜索问题" class="input-keywords" v-model="keyWords" @keydown.enter.native="searchForumQuestion(keyWords)"> </el-input
        ><el-button slot="append" icon="el-icon-search" @click="searchForumQuestion(keyWords)">搜索</el-button>
      </div>
      <div class="writeQuestion">
        <h2 @click="askQuestion()">提问</h2>
      </div>
    </div>

    <div class="m-contain">
      <div class="topic-plus-tip">
            <p id="tip-title">话题发起指南</p>
            <ul class="tip-list">
              <li>1.话题标题：请用精简的语言描述您发布的话题，不超过25字</li>
              <li>2.话题补充：详细补充您的话题内容，并确保话题描述清晰直观，并提供一些相关的资料</li>
              <li>3.选择标签：选择一个或者多个合适的标签，用逗号隔开，每个标签不超过10个字</li>
            </ul>
      </div>
      <div class="topic-plus">
            <i class="el-icon-plus"></i><span id="find-title">发起</span>
            <el-divider></el-divider>
            <el-form :model="question" label-position="top" label-width="80px" :rules="rules" ref="ruleForm" >
              <el-form-item prop="title">
                <p class="question-msg-title"><b>话题标题（简单扼要）:</b></p>
                <el-input v-model="question.title" placeholder="话题标题..." style="width:100%"></el-input>
              </el-form-item>
              <el-form-item>
                <p class="question-msg-title"><b>话题补充（必填，请参照右侧提示）:</b></p>
                <mavon-editor v-model="question.description" ref=md  @imgAdd="imgAdd" :toolbars="toolbars"/>
              </el-form-item>
              <el-form-item>
                <p class="question-msg-title"><b>添加标签：</b></p>
                  <el-tag
                    :key="tag"
                    v-for="tag in dynamicTags"
                    closable
                    :disable-transitions="false"
                    @close="handleClose(tag)">
                    {{tag}}
                  </el-tag>
                <!-- <el-input v-model="question.tag" style="width: 100%"></el-input> -->
                
                <!-- <span class="span-new-tag" size="small" @mouseenter="showInput">+ New Tag</span> -->
                <el-popover
                  placement="top-start"
                  width="600px"
                  trigger="hover">
                  <el-tabs tab-position="left">             
                    <el-tab-pane v-for="(tagTuple, firstLevelIndex) in questionTags" :key="tagTuple.name" :label="tagTuple.name">
                      <el-tag :key="tag"
                        v-for="(tag, secondLevelIndex) in tagTuple.tags" @click="selectTag(tag, firstLevelIndex, secondLevelIndex)" :id="'tag' + firstLevelIndex + secondLevelIndex" style="">{{tag}}</el-tag>
                    </el-tab-pane>
                  </el-tabs>
                  <el-button class="button-new-tag" size="small" slot="reference">+ New Tag</el-button>
                </el-popover>
              </el-form-item>
              <el-form-item>
                <el-button type="success" id="submit-btn" @click="publish('ruleForm')">发布</el-button>
              </el-form-item>
          </el-form>
      </div>
      
    </div>
  </div>
</template>

<script>
import cookie from "js-cookie";
import forumApi from '@/api/forum'

export default {
  data() {
    return {
        url: 'https://s1.ax1x.com/2023/04/03/pphIDK0.jpg',
        question: {
          title: '',
          description: '',
          tag: '',
          creatorId: ''
        },
        toolbars: {
          bold: true, // 粗体
          italic: true, // 斜体
          header: true, // 标题
          underline: true, // 下划线
          strikethrough: true, // 中划线
          mark: false, // 标记
          superscript: false, // 上角标
          subscript: false, // 下角标
          quote: true, // 引用
          ol: true, // 有序列表
          ul: true, // 无序列表
          link: true, // 链接
          imagelink: true, // 图片链接
          code: true, // code
          table: true, // 表格
          fullscreen: true, // 全屏编辑
          readmodel: false, // 沉浸式阅读
          htmlcode: true, // 展示html源码
          help: false, // 帮助
          /* 1.3.5 */
          undo: true, // 上一步
          redo: false, // 下一步
          trash: false, // 清空
          save: false, // 保存（触发events中的save事件）
          /* 1.4.2 */
          navigation: false, // 导航目录
          /* 2.1.8 */
          alignleft: true, // 左对齐
          aligncenter: true, // 居中
          alignright: true, // 右对齐
          /* 2.2.1 */
          subfield: true, // 单双栏模式
          preview: true, // 预览
          boxShadow: false
        },
        rules: {
          title: [
            { required: true, message: '请输入话题标题', trigger: 'blur' },
            { min: 1, trigger: 'blur' }
          ]
        },
        questionTags: [
          {name: '物联网学习', tags: ['物联网技术', '万物互联', '技术成长', '技术路线']},
         
        ],
        dynamicTags: [],
        keyWords: '',
    };
  },

  created() {
    this.getInfo()
  },

  methods: {
    searchForumQuestion(keyWords) {
      this.$router.push({path:'/forum/', query:{searchKeyWords:keyWords}})
    },

    selectTag(tag, firstLevelIndex, secondLevelIndex) {
      if (this.dynamicTags.length >= 5) {
        this.$message('最多添加五个标签');
        return
      }
      if (this.dynamicTags.indexOf(tag) === -1) {
        this.dynamicTags.push(tag);
        var tagId = 'tag' + firstLevelIndex + secondLevelIndex
        var node = document.getElementById(tagId)
        node.style.color = 'green'
      }
    },

    handleClose(tag) {
      this.dynamicTags.splice(this.dynamicTags.indexOf(tag), 1);
      for (let i = 0; i < this.questionTags.length; i++) {
        var tags = this.questionTags[i].tags
        for (let j = 0; j < tags.length; j++) {
          if (tags[j] === tag) {
            document.getElementById('tag' + i + j).style.color = ''
          }
        }
      }
    },

    getInfo() {
      //从cookie获取用户信息
      var userStr = cookie.get('ucenter')
      // 把字符串转换json对象(js对象)
      if(userStr) {
        this.question.creatorId = (JSON.parse(userStr)).id
      }
    },
    publish(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          var tag = ''
          for (let i = 0; i < this.dynamicTags.length; i++) {
            tag = tag + this.dynamicTags[i] + '|'
          }
          this.question.tag = tag.slice(0, tag.length - 1)
          forumApi.addQuestion(this.question)
            .then(response => {
                this.$router.push('/forum')
          })
        } else {
          console.log('error submit!!');
          return false;
        }
      });
      
    },
    //markdown编辑器的 图片上传功能
    imgAdd(pos, $file) {
      console.log('图片上传')
      console.log(pos, $file);

      var formdata = new FormData();
      formdata.append('image', $file);
      console.log(formdata)
      forumApi.uploadOssFile(formdata)
        .then(response => {
            console.log('请求成功')
            console.log(response.data.data.url)
            this.$refs.md.$img2Url(pos, response.data.data.url)
      })

    },
    askQuestion() {
      this.$message({
        message: "请先完成当前话题编辑！",
        type: "info",
      });
    },
  },
};
</script>

<style scoped>
h1 {
  font-size: 28px;
  /* color: #7c7c7c; */
}

h2 {
  font-size: 20px;
  /* color: #7c7c7c; */
}

.content {
  /* 上 右 下 左 */
  margin: 10px 0px 0px 0px;
  /* padding-bottom: 100px; */
}

.top-contain {
  max-width: 1150px;
  margin: 0 auto;
  align-items: center;
  display: flex;
  position: relative;
}
.logoBlock {
  width: 10%;
  padding: 5px;
  display: inline-block;
}
.searchQuestion {
  vertical-align: top;
  display: inline-block;
  position: absolute;
  left: 150px;
}
.input-keywords {
  /* 搜索框长度 */
  width: 300px;
  margin-right: 10px;
}
.writeQuestion {
  /* https://blog.csdn.net/qq_44131760/article/details/104755826  解释了为什么使用 vertical-align*/
  vertical-align: top;
  display: inline-block;
  position: absolute;
  right: 10px;
}

.m-contain {
  max-width: 1150px;
  margin: 0 auto;
  margin-top: 20px;
}

.topic-plus {
    width: 70%;
}

.topic-plus-tip {
    float: right;
    width: 28%;
    height: 77px;
}

.el-icon-plus {
    font-size: 30px;
}

#find-title {
    margin-left: 10px;
    font-size: 30px;
    font-weight: bold;
}

#tip-title {
    font-size: 30px;
    font-weight: bold;
}

.question-msg-title {
  font-size: 20px;
}

#submit-btn {
  /* 右侧显示发布按钮 */
  float: right;
}

.tip-list {
  font-size: 18px;
}

.el-tag + .el-tag {
  margin-left: 10px;
}

.button-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}

</style>